// WebPush 推送
self.addEventListener('push', event => {
	let data = {};
	try {
		data = event.data ? JSON.parse(event.data.text()) : {};
	} catch {
		data = {
			title: '新通知',
			body: event.data?.text() || ''
		};
	}

	const title = data.title || '新通知';
	const options = {
		body: data.body || '您有一条新消息',
		icon: data.icon || '/static/logo.png',
		badge: data.badge || '/static/logo.png',
		data: data.data || {}
	};

	event.waitUntil(self.registration.showNotification(title, options));
});

// 监听来自页面的消息
self.addEventListener('message', event => {
	if (event.data && event.data.type === 'SHOW_CHAT_NOTIFICATION') {
		const {
			title,
			body,
			icon,
			badge,
			conversation_id,
			message_data
		} = event.data.data;

		event.waitUntil(
			self.registration.showNotification(title, {
				body: body,
				icon: icon,
				badge: badge,
				tag: 'chat-message',
				data: {
					conversation_id: conversation_id,
					type: 'chatMessage',
					message_data: message_data
				}
			})
		);
	}
});

self.addEventListener('notificationclick', function(event) {
	event.notification.close();

	if (event.action === 'open') {
		// 点击"打开"按钮，跳转到聊天页面
		const conversationId = event.notification.data?.conversation_id;

		event.waitUntil(
			clients.matchAll({
				type: 'window'
			}).then(windowClients => {
				// 检查是否已经有打开的窗口
				for (let client of windowClients) {
					if (client.url.includes('/#/pages/chat/list/index') && 'focus' in client) {
						return client.focus();
					}
				}

				// 打开聊天页面
				return clients.openWindow('/#/pages/chat/list/index');
			})
		);
	}
});